package lightswitch.client.code.gui;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.ImageIcon;

import lightswitch.client.code.extension.BackgroundPanel;
import lightswitch.client.code.model.MyTableModel;
import lightswitch.code.connection.ConnectionHelper;
import lightswitch.code.connection.QueryDataTransfering;

import java.awt.event.MouseAdapter;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;

public class MainFrame extends JFrame {

    private static JPanel contentPane;
    private JTextArea textField;
    public static ConnectionHelper helper;
    private static JScrollPane scrollPane;
    protected static JTable jTable;
    private static JPanel panelResult;
    public static Icon connectIcon;
    public static Icon closeConnectIcon;
    public static Icon checkIcon;
    public static Icon executeIcon;
    public static Icon aboutIcon;
    public static JLabel lblStateQuery;
    public static MainFrame mainFrame;
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    mainFrame = new MainFrame();
                    mainFrame.setVisible(true);
                    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    mainFrame.addWindowListener(new WindowAdapter() {
                       @Override
                       public void windowClosing(WindowEvent we) {
                           int result = JOptionPane.showConfirmDialog(null, "Exit program?", "Confirm",
                                   JOptionPane.OK_CANCEL_OPTION);
                           
                           if (result == JOptionPane.OK_OPTION){
                               System.exit(1);
                           } else {
                               return;
                           }

                       }
                   });
                    new ShowStatusThread().start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MainFrame() {
        setIconImage(Toolkit.getDefaultToolkit().getImage("icon.jpg"));
        // Load image
        connectIcon = new ImageIcon("connect-icon.png");
        closeConnectIcon = new ImageIcon("close-icon.png");
        checkIcon = new ImageIcon("check-icon.png");
        executeIcon = new ImageIcon("execute-icon.png");
        aboutIcon = new ImageIcon("about-icon.png");

        setResizable(false);

        // init helper XXX
        helper = new ConnectionHelper();
        // ///////////////////////

        setTitle("SQL Client");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 400);
        contentPane = new BackgroundPanel();
        ((BackgroundPanel)contentPane).setBG("bg_client.png");
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(0, 0, 594, 25);
        contentPane.add(menuBar);

        JMenu mnConnection = new JMenu("Connection");
        menuBar.add(mnConnection);

        JMenuItem mntmConnectToServer = new JMenuItem("Connect to server");
        mntmConnectToServer.setIcon(connectIcon);
        mntmConnectToServer.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent arg0) {
                if (ConnectionHelper.clientSocket!=null && ConnectionHelper.clientSocket.isConnected()) {
                    int result = JOptionPane.showConfirmDialog(null,
                            "System is connecting to " + helper.getConnectionIP() + "Close this connection any way?",
                            "Confirm", JOptionPane.OK_CANCEL_OPTION);
                    if (result == JOptionPane.OK_OPTION) {
                        if (!helper.disConnect()) {
                            JOptionPane.showMessageDialog(null, "Cannot disconnect!\nRetry later! ", "Message", 1);
                        }
                    } else {
                        return;
                    }
                }

                JTextField ip = new JTextField(helper.getConnectionIP());
                JTextField port = new JTextField(String.valueOf(helper.getPort()));

                JComponent[] inputs = new JComponent[]{new JLabel("IP:"), ip, new JLabel("Port: "), port};

                int res = JOptionPane.showConfirmDialog(null, inputs, "Connect to", JOptionPane.OK_CANCEL_OPTION);

                if (res == JOptionPane.OK_OPTION) {
                    try {
                        String ipRes = ip.getText();
                        int portRes = Integer.parseInt(port.getText());
                        helper.setConnectionIP(ipRes);
                        helper.setPort(portRes);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "IP/Port is invalid! Connect later.", "Message", 1);
                        return;
                    }
                }

                if (ConnectionHelper.connect()) {
                    // show dialog connect success
                    JOptionPane.showMessageDialog(null, "Connect success", "Message", 1);
                    return;
                }
                // show dialog connect fail
                JOptionPane.showMessageDialog(null, "Cannot connect to server!\nCheck ip/port & retry later! ",
                        "Message", 1);
                return;
            }
        });
        mnConnection.add(mntmConnectToServer);

        JMenuItem mntmNewMenuItem = new JMenuItem("Close connection");
        mntmNewMenuItem.setIcon(closeConnectIcon);
        mntmNewMenuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int result = JOptionPane
                        .showConfirmDialog(null, "Disconnect?", "Confirm", JOptionPane.OK_CANCEL_OPTION);
                if (result == JOptionPane.OK_OPTION) {
                    if (!helper.disConnect()) {
                        JOptionPane.showMessageDialog(null, "Cannot disconnect!\nRetry later! ", "Message", 1);
                        return;
                    }
                }
            }
        });
        mnConnection.add(mntmNewMenuItem);

        JMenu mnCommand = new JMenu("Command");
        menuBar.add(mnCommand);

        JMenuItem mntmCheckQuery = new JMenuItem("Check query");
        mntmCheckQuery.setIcon(checkIcon);
        mntmCheckQuery.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                String query = textField.getText();
                if (ConnectionHelper.checkQuery(query)) {
                    // show dialog
                    JOptionPane.showMessageDialog(null, "Query is valid", "Message", 1);
                    return;
                }
                // show dialog
                JOptionPane.showMessageDialog(null, "Query is invalid", "Message", 1);
                return;
            }
        });
        mnCommand.add(mntmCheckQuery);

        JMenuItem menuItem = new JMenuItem("Execute query");
        menuItem.setIcon(executeIcon);
        menuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (ConnectionHelper.clientSocket!=null && ConnectionHelper.clientSocket.isConnected()) {
                    helper.send(textField.getText());
                    repaint();
                    return;
                }
                // show dialog connect fail
                JOptionPane.showMessageDialog(null,
                        "Cannot connect to server!\nPlease choose Connection --> Connect to server! ", "Message", 1);

            }
        });
        mnCommand.add(menuItem);

        JMenu mnHelp = new JMenu("Help");
        menuBar.add(mnHelp);

        JMenuItem mntmAbout = new JMenuItem("About");
        mntmAbout.setIcon(aboutIcon);
        mntmAbout.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                // show dialog about
                JOptionPane.showMessageDialog(null,
                        "Lightswitch client v1.0\n0912005--Tr?n Th? M? Dung\n0912149--Ph?m Thu?n Hi?u", "About", 1);
            }
        });
        mnHelp.add(mntmAbout);

        panelResult = new BackgroundPanel();
        ((BackgroundPanel)panelResult).setBG("bg_result.jpg");
        panelResult.setBounds(10, 58, 570, 179);
        contentPane.add(panelResult);

        JPanel panel = new JPanel();
        panel.setBounds(10, 275, 570, 84);
        contentPane.add(panel);
        panel.setLayout(null);
        textField = new JTextArea();
        JScrollPane sbrText = new JScrollPane(textField);
        sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        sbrText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent arg0) {
                //lblStateQuery.setText("typing");
            }
        });
        sbrText.setBounds(0, 0, 509, 84);
        panel.add(sbrText);
        textField.setColumns(10);

        Icon imageIcon = new ImageIcon("Play-Normal-icon.png");
        JButton btnNewButton = new JButton("");
        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (ConnectionHelper.clientSocket!=null && ConnectionHelper.clientSocket.isConnected()) {
                    helper.send(textField.getText());
                    repaint();
                    return;
                }
                // show dialog connect fail
                JOptionPane.showMessageDialog(null,
                        "Cannot connect to server!\nPlease choose Connection --> Connect to server! ", "Message", 1);
            }
        });
        btnNewButton.setIcon(imageIcon);
        btnNewButton.setBounds(509, 0, 61, 84);

        panel.add(btnNewButton);
        
        JLabel lblResult = new JLabel("Result");
        lblResult.setForeground(Color.BLUE);
        lblResult.setFont(new Font("Tahoma", Font.PLAIN, 20));
        lblResult.setBounds(10, 29, 115, 25);
        contentPane.add(lblResult);
        
        JLabel lblQuery = new JLabel("Query");
        lblQuery.setForeground(Color.BLUE);
        lblQuery.setFont(new Font("Tahoma", Font.PLAIN, 20));
        lblQuery.setBounds(10, 245, 115, 25);
        contentPane.add(lblQuery);
        
        lblStateQuery = new JLabel("");
        lblStateQuery.setBounds(436, 246, 133, 16);
        contentPane.add(lblStateQuery);

    }

    public static void initJTable(QueryDataTransfering tb) {
        if (scrollPane != null) {
            panelResult.remove(scrollPane);
            panelResult.repaint();
        }
        MyTableModel model = tb.convertToModel();
        jTable = new JTable(model);
        jTable.setAutoCreateRowSorter(true);
        scrollPane = new JScrollPane(jTable);
        scrollPane.setAutoscrolls(true);
        scrollPane.setBounds(0, 0, 570, 180);
        panelResult.add(scrollPane);
        panelResult.repaint();
    }
}

class ShowStatusThread extends Thread {
    public void run() {
        String constStr = "Lightswitch - SQL client ";
        int count = 0;
        int max = 45;
        int delta=1;
        while(true){
            try {
                String status = (ConnectionHelper.clientSocket!=null && ConnectionHelper.clientSocket.isConnected())?"Connected":"Not_connect";
                count+=delta;
                if(count>max || count<0){
                    delta*=-1;
                }
                
                String showStatus = constStr;
                for (int i = 0; i<max; i++){
                    if (i<count){
                        showStatus+=" ";
                    }
                }
                showStatus+=status;
                MainFrame.mainFrame.setTitle(showStatus);   
                this.sleep(100);
            } catch (InterruptedException ex) {
                // TODO Auto-generated catch block
                ex.printStackTrace();
            }
        }
    }
}
